package util;

import org.springframework.web.multipart.MultipartFile;
import winkyle.woodenfish.android.exception.FileStoreException;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author winkyle
 * @date 2018/06/22
 * @description 文件存储工具类
 */
public class FileStoreUtil {
	/**
	 * @description 保存图片，并返回相对路径
	 * @param path
	 * @param headPortrait
	 * @return
	 * @throws IOException
	 */
	public static String storeImge(String path, MultipartFile headPortrait){
		String filePath = getFileStoragePath(path, headPortrait.getContentType(),"png|jpe?g|bmp");
		BufferedOutputStream out;
		try {
			out = new BufferedOutputStream(new FileOutputStream(new File(path+filePath)));
			out.write(headPortrait.getBytes());
			out.flush();
			out.close();
		} catch (IOException e) {
			throw new FileStoreException("存入失败");
		}
		return filePath;
	}

	/**
	 * @description 获取图片保存路径
	 * @param path
	 * @param contentType
	 * @param suffix
	 * @return
	 */
	private static String getFileStoragePath(String path, String contentType, String suffix) {
		Pattern r = Pattern.compile(suffix);
		Matcher m = r.matcher(contentType);
		if (contentType == null || contentType.isEmpty() || !m.find()) {
			throw new FileStoreException("类型错误");
		}
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
		String filePath = String.format("%s.%s",System.currentTimeMillis(),contentType.replace("image/", ""));
		return filePath;
	}
}
